import Joi from 'joi';
import debugCheck from '@kuiper-helpers/debug-check';
import joiToFilterArg from '../helpers/joiToFilterArg';

const notification = Joi.object({
	_id: Joi.string(),
	title: Joi.string().description('标题'),
	category: Joi.string().description('类别'),
	message: Joi.string().description('消息'),
	from: Joi.string().description('发送者'),
	to: Joi.array().items(Joi.string()).description('接收者'),
	level: Joi.string().description('等级'),
	data: Joi.object({
		taskCategory: Joi.string().description('任务类别'),
	})
		.unknown()
		.allow(null)
		.description('附加信息'),
	datetime: Joi.string().description('发送时间'),
	isMarked: Joi.boolean().description('是否已读'),
	isMarkedMap: Joi.object().unknown().description('已读状态'),
	action: Joi.object().unknown().description('操作'),
	choosedActionMap: Joi.object().unknown().description('选择操作'),
});

export const pagination = {
	tags: ['api', 'notification'],
	description: '站内信列表-分页查看',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		payload: Joi.object({
			page: Joi.number().default(1).description('当前页'),
			perPage: Joi.number().default(10).description('每页条目数'),
			filter: joiToFilterArg(notification)
				.append({
					datetimeGTE: Joi.date().description('发送时间大于等于'),
					datetimeLTE: Joi.date().description('发送时间小于等于'),
					titleSearch: Joi.string().allow(null),
				})
				.description('过滤条件'),
		}),
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				NotificationPagination: Joi.object({
					count: Joi.number().description('总条数'),
					pageInfo: Joi.object({
						currentPage: Joi.number().description('当前页数'),
						perPage: Joi.number().description('每页条数'),
						pageCount: Joi.number().description('总页数'),
						itemCount: Joi.number().description('总条数'),
						hasNextPage: Joi.boolean().description('是否有下一页'),
						hasPreviousPage: Joi.boolean().description('是否有上一页'),
					}),
					items: Joi.array().items(
						notification.append({
							toUsers: Joi.array().items(
								Joi.object({
									_id: Joi.string(),
									username: Joi.string(),
								})
							),
							fromUser: Joi.object({
								_id: Joi.string(),
								username: Joi.string(),
							}).allow(null),
						})
					),
				}),
			}),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const {
					payload: { page, perPage, filter },
				} = request;

				return JSON.stringify({
					variables: { page, perPage, filter },
					// #region query
					query: `
						query($page: Int = 1, $perPage: Int = 10, $filter: FilterFindManyNotificationInput, $sort: SortFindManyNotificationInput = _ID_DESC) {
							NotificationPagination(page: $page, perPage: $perPage, filter: $filter, sort: $sort) {
								count
								pageInfo {
									currentPage
									perPage
									pageCount
									itemCount
									hasNextPage
									hasPreviousPage
								}
								items {
									_id
									title
									category
									message
									from
									to
									level
									data
									datetime
									isMarked
									isMarkedMap
									action
									choosedActionMap
									toUsers {
										_id
										username
									}
									fromUser {
										_id
										username
									}
								}
							}
						}`,
					// #endregion
				});
			},
		},
	},
};

export const createOne = {
	tags: ['api', 'notification'],
	description: '创建站内信',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		payload: Joi.object({
			title: Joi.string().description('标题'),
			category: Joi.string().default('服务公告').description('类别'),
			message: Joi.string().description('消息'),
			from: Joi.string().default('系统').description('发送者'),
			to: Joi.array().items(Joi.string()).description('接收者'),
			level: Joi.string().description('等级'),
			data: Joi.object().unknown().description('附加信息'),
			action: Joi.object().unknown().description('操作'),
		}),
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				sendNotification: notification,
			}).label('Data'),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const { payload } = request;

				return JSON.stringify({
					variables: payload,
					// #region query
					query: `
						mutation(
							$to: [String!],
							$category: String = "通知",
							$title: String!,
							$message: String!,
							$type: String,
							$from: String,
							$level: String,
							$action: JSON,
							$data: JSON,
							$isBrodcast: Boolean,
						) {
							sendNotification(
								to: $to,
								category: $category,
								title: $title,
								message: $message,
								type: $type,
								from: $from,
								level: $level,
								action: $action,
								data: $data,
								isBrodcast: $isBrodcast,
							) {
								_id
								title
								category
								message
								from
								to
								level
								data
								datetime
								isMarked
								isMarkedMap
								action
								choosedActionMap
							}
						}`,
					// #endregion
				});
			},
		},
	},
};

export const removeMany = {
	tags: ['api', 'notification'],
	description: '批量删除站内信',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		payload: Joi.array()
			.items(Joi.string().description('站内信ID'))
			.required()
			.description('站内信ID列表'),
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				NotificationRemoveMany: Joi.object({
					numAffected: Joi.number().description('删除条数'),
				}).label('NotificationRemoveMany'),
			}).label('Data'),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const { payload } = request;

				return JSON.stringify({
					variables: { _ids: payload },
					// #region query
					query: `
						mutation($_ids: [MongoID]) {
							NotificationRemoveMany(filter: { _ids: $_ids }) {
								numAffected
							}
						}`,
					// #endregion
				});
			},
		},
	},
};

export const count = {
	tags: ['api', 'notification'],
	description: '站内信数量统计',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		payload: Joi.object({
			filter: joiToFilterArg(notification).description('过滤条件'),
		}),
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				NotificationCount: Joi.number().description('数量'),
			}),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const {
					payload: { filter },
				} = request;

				return JSON.stringify({
					variables: { filter },
					// #region query
					query: `
						query($filter: FilterCountNotificationInput) {
							NotificationCount(filter: $filter)
						}`,
					// #endregion
				});
			},
		},
	},
};
